package com.qf.shiro.controller;


import com.qf.shiro.pojo.Members;
import com.qf.shiro.token.CustomToken;
import com.qf.shiro.type.LoginType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;

import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MembersController {

    //用户登陆的类型
    private static final String LOGIN_TYPE= LoginType.MEMBERS.toString();


    @RequestMapping(value = "login1")
    public String login(Members members, boolean rememberMe, Model model){

        System.out.println("[/login1]------------>" + members.toString() + "\nrememberMe------------>" + rememberMe);
        //封装成请求对象
        CustomToken customToken = new CustomToken(members.getUsername(),members.getPassword(),LOGIN_TYPE);
        //获取登陆的主体对象
        Subject subject = SecurityUtils.getSubject();
        //登陆
        try{
            subject.login(customToken);
        }catch (UnknownAccountException err){  //用户名不对

            model.addAttribute("userNameError","用户名不对");
            return "login";
        }catch (IncorrectCredentialsException err){ //说明是密码不对

            model.addAttribute("passwordError","密码不对");
            return "login";
        }catch (Exception err){

            model.addAttribute("otherError","其他问题造成登陆失败");
            return "login";
        }
        //首页要显示用户信息
        //获取用户信息
        //这个方法返回的数据 实际上就是 realm中认证的SimpleAuthticationInfo的第一个参数的数据
        Members members1= (Members) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("members",members1);
        return "index1";
    }
}
